package com.eliauk.democommon.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyuncs.utils.StringUtils;
import com.eliauk.democommon.common.aliyun.OssProperties;
import com.eliauk.democommon.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private OssProperties ossProperties;


    public String upload(byte[] bytes, String filename) {
        String newFileName = makeFileName(filename);

        try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            ossClient.putObject(ossProperties.getBucket(), newFileName, inputStream, objectMetadata);

            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(ossProperties.getBucket(), newFileName, HttpMethod.GET);
            Date expiration = new Date(System.currentTimeMillis() + (long) Math.pow(10, 10));
            urlRequest.setExpiration(expiration);
            URL url = ossClient.generatePresignedUrl(urlRequest);


            return url.toString().split("\\?")[0];
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败：" + e.getMessage());
        }
    }


    public void delete(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            // TODO 文件完整路径
            String ossAccessDomainUrl = "https://"+ossProperties.getEndpoint() + "/"+ossProperties.getBucket() + "/";
            fileUrl = fileUrl.replaceFirst(ossAccessDomainUrl, "");
            ossClient.deleteObject(ossProperties.getBucket(), fileUrl);
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
        }
    }

    public String makeFileName(String filename){
        String today = DateUtil.format(new Date(), "yyyyMMdd");
        return   today + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + FileUtil.getSuffix(filename);
    }
}
